package com.base.pub.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DateUtils {

	private static String[] parsePatterns = { "yyyy-MM-dd",
			"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd",
			"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd",
			"yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM" };

	public static final String FORMAT_DATE_1 = "yyyy/MM/dd HH:mm:ss";

	public static Date parseDate(Object str) {
		try {
			return org.apache.commons.lang3.time.DateUtils.parseDate(
					str.toString(), parsePatterns);
		} catch (ParseException e) {
			return null;
		}
	}

	public static String getTimes(Date date, String timeType) {
		SimpleDateFormat sf = new SimpleDateFormat(timeType);
		return sf.format(date);
	}

	public static String getTimes(long timemilli, String timeType) {
		SimpleDateFormat sf = new SimpleDateFormat(timeType);
		return sf.format(new Date(timemilli));
	}

	public static Long getDigit(String a) {
		String regEx = "[^0-9]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(a);
		return Long.parseLong(m.replaceAll("").trim());
	}

	public static long getTimeSec(String date, String timeType)
			throws ParseException {
		SimpleDateFormat sf = new SimpleDateFormat(timeType);
		return sf.parse(date).getTime();
	}

	// 获得某天0点时间
	public static int getTimesMorning(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return (int) (cal.getTimeInMillis());
	}

	// 获得某天24点时间
	public static int getTimesNight(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 24);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return (int) (cal.getTimeInMillis());
	}

	// 获得本周一0点时间
	public static int getTimesWeekMorning(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY),
				cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		return (int) (cal.getTimeInMillis());
	}

	// 获得本周日24点时间
	public static int getTimesWeekNight(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY),
				cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		return (int) ((cal.getTime().getTime() + (7 * 24 * 60 * 60 * 1000)));
	}

	/**
	 * 某月天数
	 * 
	 * @return
	 */
	public static int getDayOfMonth(Date date) {
		Calendar cal = Calendar.getInstance(Locale.CHINA);
		cal.setTime(date);
		int day = cal.getActualMaximum(Calendar.DATE);
		return day;
	}
}
